package com.freesome.flii
{
	import flash.errors.*;
	import flash.events.*;
	import flash.net.Socket;
	import com.freesome.flii.Flii;

	public class FliiSocketReader extends Socket
	{
    	private var response:String;

	    public function FliiSocketReader(host:String = null, port:uint = 0) {
	        super(host, port);
	        configureListeners();
	    }
	
	    private function configureListeners():void {
	        addEventListener(Event.CLOSE, closeHandler);
	        addEventListener(Event.CONNECT, connectHandler);
	        addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
	        addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
	        addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
	    }
	
	    private function writeln(str:String):void {
	        str += "\n";
	        try {
	            writeUTFBytes(str);
	        }
	        catch(e:IOError) {
	            trace(e);
	        }
	    }
	
	    private function sendRequest():void {
	        trace("sendRequest");
	        response = "";
	        writeln("GET /");
	        flush();
	    }
	
	    private function readResponse():void {
	    	Flii.currData+=bytesAvailable;
	        var str:String = readUTFBytes(bytesAvailable);
	      
	        //step through string
	        for (var i:int = 0;i<str.length;i++) {
	        	var c:String=str.charAt(i);
	        	if (c=="*") {
	        		Flii.rcSocket(response);
	        		//Flii.Log(response);
	        		response=""; 
	        		
	        	} else {
	        		response+=c;
	        	}	        	
	        }       
	       
	    }
	
	    private function closeHandler(event:Event):void {
	        trace("closeHandler: " + event);
	        trace(response.toString());
	    }
	
	    private function connectHandler(event:Event):void {
	        trace("connectHandler: " + event);
	        sendRequest();
	    }
	
	    private function ioErrorHandler(event:IOErrorEvent):void {
	        trace("ioErrorHandler: " + event);
	    }
	
	    private function securityErrorHandler(event:SecurityErrorEvent):void {
	        trace("securityErrorHandler: " + event);
	    }
	
	    private function socketDataHandler(event:ProgressEvent):void {
	        trace("socketDataHandler: " + event);
	        readResponse();
	    }		
	}
}